package a11_单调栈;

import java.util.Stack;

/**
 * <p>
 * a04_接雨水复习1
 * </p>
 *
 * @author flyduck
 * @since 2025/3/10
 */
public class a04_接雨水复习1 {
    public int trap(int[] nums) {
        int result = 0;

        Stack<Integer> stack = new Stack<>();
        stack.push(0);

        for (int i = 1; i < nums.length; i++) {
            while (!stack.isEmpty() && nums[stack.peek()] < nums[i]){
                Integer pop = stack.pop();
                if(!stack.isEmpty()){
                    int height = Math.min(nums[i] , nums[stack.peek()]) - nums[pop];
                    int width = i - stack.peek() - 1;
                    result = result + (height * width);
                }
            }
            stack.push(i);
        }
        return result;
    }
}
